package xyz.masaikk;
import java.lang.Math;
public class PipeFilter {
    public int[] chessboard;
    public int [][] chessboardTemp;
    public int k;
    public int numOfSolution;
    public int numOfQueens;

    public PipeFilter(int numOfQueen) {
        numOfQueens=numOfQueen;
        chessboard = new int[numOfQueens];
        int d = numOfAllSolution(numOfQueens);
        chessboardTemp = new int [d][numOfQueens];

        for (int i = 0; i < numOfQueens; i++)
        {
            chessboard[i] = i + 1;

        }
        numOfSolution=0;
        k=0;
    }
    public void swap(int a, int b)
    {
        int temp;
        temp = a;
        a = b;
        b = temp;
    }

    public boolean canPlace(int[] chess)//判断某个位置是否可以放置棋子
    {
        for (int i = 0; i < numOfQueens; i++)
        {
            for (int j = i + 1; j < numOfQueens; j++)
            {
                if (Math.abs(i - j) == Math.abs(chess[i] - chess[j]))
                {
                    return  false;
                }
            }
        }

        return true;
    }

    public void allSolution(int n)
    {
        int num=n;
        if (num == 1)
        {
            for (int i = 0; i < numOfQueens; i++)
            {
                chessboardTemp[k][i] = chessboard[i];//棋子在棋盘上的位置
            }
            k=k+1;
        }
        else
        {
            for (int i = 0; i < num; i++)
            {
                int temp1=chessboard[i];
                chessboard[i]=chessboard[num-1] ;
                chessboard[num-1]= temp1;

                allSolution(num-1);

                int temp2=chessboard[i];
                chessboard[i]=chessboard[num-1] ;
                chessboard[num-1]= temp2;
            }
        }
    }

    public int numOfAllSolution(int n)//情况数
    {
        if (n == 0)
        {
            return 0;
        }
        else {
            int num = 1;
            while (n >= 2)
                num = num * (n--);
            return num;
        }
    }

    public int Pipe(int num)//返回情况数
    {
        allSolution(num);
        for (int i = 0; i < numOfAllSolution(num); i++)
        {

            if (canPlace(chessboardTemp[i]) == true)//棋子可以放置，情况数+1
            {
                numOfSolution++;
            }
        }

        return numOfSolution;
    }

    public int getResult()//返回情况数
    {
        return Pipe(numOfQueens);
    }
}
